package com.fire.control.system.module.common.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fire.control.system.support.protocol.comman.ResponseJsonProtocol;
import com.fire.control.system.support.util.HttpUtil;


@RestController
public class MyErrorController implements ErrorController{

    private static final Logger logger = LoggerFactory.getLogger(MyErrorController.class);
    
	@Override
	public String getErrorPath() {
		return "/error";
	}
	
	@RequestMapping("error")
    public void error(HttpServletRequest request,HttpServletResponse response) {
        HttpStatus httpStatus = getStatus(request);
        ResponseJsonProtocol jsonProtocol =	new ResponseJsonProtocol(httpStatus.value(), httpStatus.getReasonPhrase(), false);
        HttpUtil.outputJson(response, jsonProtocol.toString());
    }
	
	private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode != null) {
            try {
                return HttpStatus.valueOf(statusCode);
            }
            catch (Exception ex) {
            }
        }
        return HttpStatus.INTERNAL_SERVER_ERROR;
    }   

}